<template>
  <div v-if="visible" class="cover-editor-overlay">
    <div class="cover-editor-modal">
      <!-- 顶部标题栏 -->
      <div class="modal-header">
        <h2>编辑封面</h2>
        <div class="header-buttons">
          <button class="cancel-button" @click="handleCancel">取消编辑</button>
          <button class="confirm-button" @click="handleConfirm">完成</button>
        </div>
      </div>
      <div class="modal-content">
        <!-- 左侧历史封面 -->
        <div class="history-section">
          <div class="history-item current">
            <div class="preview-thumbnail">正在使用</div>
          </div>
        </div>
        <!-- 中间预览区域 -->
        <div class="preview-section">
          <div class="canvas-container" ref="canvasContainer">
            <div class="preview-area">
              <!-- 封面预览内容 -->
              <div class="cover-preview">
                <!-- 动态内容项 -->
                <div
                    v-for="item in contentItems"
                    :key="item.id"
                    :class="['content-item', { 'dragging': draggingItem?.id === item.id }]"
                    :style="{
                  left: '50%',
                  transform: 'translateX(-50%)',
                  top: `${item.position.y}px`,
                  fontSize: getFontSize(item.type),
                  fontFamily: selectedFont,
                  textAlign: 'center',
                  width: '80%'
                }"
                    @mousedown.stop="startDragging(item, $event)"
                    @dblclick.stop="startEditing(item)"
                >
                  <template v-if="editingItem?.id === item.id">
                    <input
                        ref="editInput"
                        v-model="item.text"
                        class="edit-input"
                        @blur="finishEditing"
                        @keyup.enter="finishEditing"
                        :style="{
                      fontSize: getFontSize(item.type),
                      fontFamily: selectedFont,
                      textAlign: 'center',
                      width: '100%'
                    }"
                    />
                  </template>
                  <template v-else>
                    {{ item.text }}
                  </template>
                </div>
                <!-- 申报信息区域 -->
                <div
                    v-if="showDeclaration"
                    class="declaration-info"
                    :class="{ 'dragging': isDraggingDeclaration }"
                    :style="{
                  left: '50%',
                  transform: 'translateX(-50%)',
                  top: `${declarationPosition.y}px`
                }"
                    @mousedown.stop="startDraggingDeclaration"
                    @mouseenter="showRemoveButton = true"
                    @mouseleave="showRemoveButton = false"
                >
                  <div class="declaration-row">
                  <span
                      class="declaration-label"
                      @dblclick.stop="startEditingLabel('person')"
                  >
                    <template v-if="editingLabel === 'person'">
                      <input
                          ref="labelInput"
                          v-model="labels.person"
                          class="label-input"
                          @blur="finishEditingLabel"
                          @keyup.enter="finishEditingLabel"
                      />
                    </template>
                    <template v-else>
                      {{ labels.person }}：
                    </template>
                  </span>
                    <div class="declaration-input-wrapper">
                      <input
                          v-model="declarationInfo.person"
                          class="declaration-input"
                          :style="{ fontFamily: selectedFont, textAlign: 'center' }"
                          placeholder="请输入申报人姓名"
                      />
                    </div>
                  </div>
                  <div class="declaration-row">
                  <span
                      class="declaration-label"
                      @dblclick.stop="startEditingLabel('unit')"
                  >
                    <template v-if="editingLabel === 'unit'">
                      <input
                          ref="labelInput"
                          v-model="labels.unit"
                          class="label-input"
                          @blur="finishEditingLabel"
                          @keyup.enter="finishEditingLabel"
                      />
                    </template>
                    <template v-else>
                      {{ labels.unit }}：
                    </template>
                  </span>
                    <div class="declaration-input-wrapper">
                      <input
                          v-model="declarationInfo.unit"
                          class="declaration-input"
                          :style="{ fontFamily: selectedFont, textAlign: 'center' }"
                          placeholder="请输入申报单位"
                      />
                    </div>
                  </div>
                  <button
                      v-if="showRemoveButton"
                      class="remove-button"
                      @click.stop="removeDeclaration"
                  >
                    ×
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧编辑区域 -->
        <div class="edit-section">
          <!-- 字体选择 -->
          <div class="edit-group">
            <div class="group-title">字体</div>
            <div class="font-options">
              <label class="font-option">
                <input
                    type="radio"
                    v-model="selectedFont"
                    value="SimHei, 黑体"
                    class="sr-only"
                />
                <span class="font-label" :class="{ active: selectedFont === 'SimHei, 黑体' }">
                黑体
              </span>
              </label>
              <label class="font-option">
                <input
                    type="radio"
                    v-model="selectedFont"
                    value="SimSun, 宋体"
                    class="sr-only"
                />
                <span class="font-label" :class="{ active: selectedFont === 'SimSun, 宋体' }">
                宋体
              </span>
              </label>
            </div>
            <div class="font-tip">请先选择封面内容再选择字体</div>
          </div>
          <!-- 插入功能 -->
          <div class="edit-group">
            <div class="group-title">插入</div>
            <div class="insert-options">
              <button class="insert-button" @click="insertContent('h1')">插入一级标题</button>
              <button class="insert-button" @click="insertContent('h2')">插入二级标题</button>
              <button class="insert-button" @click="insertContent('h3')">插入三级标题</button>
              <button class="insert-button" @click="insertContent('text')">插入文字</button>
              <div class="bottom-insert">
                <button class="insert-button date" @click="insertContent('date')">
                  插入日期
                </button>
                <button
                    v-if="!showDeclaration"
                    class="insert-button"
                    @click="addDeclaration"
                >
                  添加申报信息
                </button>
              </div>
            </div>
            <div class="insert-tip">点击模板页任何位置即可添加所需要的内容</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  initialCoverData: {
    type: Object,
    default: () => ({
      contentItems: [], // New: Array for dynamic content
      font: 'SimHei, 黑体', // New: Font selection
      declarationInfo: {
        person: '',
        unit: '',
        position: { y: 400 }, // New: Position for declaration info
        labels: {
          person: '申报人',
          unit: '申报单位'
        }
      }
    })
  }
})

const emit = defineEmits(['update:visible', 'confirm', 'cancel'])

// 响应式状态
const selectedFont = ref('SimHei, 黑体')
const canvasContainer = ref(null)
const editInput = ref(null)
const labelInput = ref(null)
const contentItems = ref([])
const draggingItem = ref(null)
const editingItem = ref(null)
const dragOffset = ref({ x: 0, y: 0 })

// 申报信息相关状态
const declarationInfo = ref({
  person: '',
  unit: ''
})
const declarationPosition = ref({ y: 400 })
const isDraggingDeclaration = ref(false)
const declarationDragOffset = ref({ y: 0 })
const labels = ref({
  person: '申报人',
  unit: '申报单位'
})
const editingLabel = ref(null)
const showRemoveButton = ref(false)
const showDeclaration = ref(true) // ✅ 默认改为 true，确保申报信息区域始终显示

// 初始化数据
const initializeData = () => {
  console.log('CoverEditor: 初始化封面数据:', JSON.parse(JSON.stringify(props.initialCoverData)))
// 清空现有内容
  contentItems.value = []
// 从 initialCoverData 填充 contentItems
  if (props.initialCoverData.contentItems && props.initialCoverData.contentItems.length > 0) {
    contentItems.value = JSON.parse(JSON.stringify(props.initialCoverData.contentItems)); // Deep copy to avoid direct mutation
  } else {
    // 如果没有 contentItems，则添加默认标题
    // 兼容旧的 title/subtitle 结构
    const defaultTitle = props.initialCoverData.title || '附件材料';
    const defaultSubtitle = props.initialCoverData.subtitle || '';
    contentItems.value.push({
      id: Date.now(),
      type: 'h1',
      text: defaultTitle,
      position: { y: 100 }
    });
    if (defaultSubtitle) {
      contentItems.value.push({
        id: Date.now() + 1,
        type: 'h2',
        text: defaultSubtitle,
        position: { y: 180 }
      });
    }
  }
// 初始化字体
  selectedFont.value = props.initialCoverData.font || 'SimHei, 黑体';

// 初始化申报信息
// 确保 declarationInfo 及其内部字段始终被初始化
  declarationInfo.value = {
    person: props.initialCoverData.declarationInfo?.person || '',
    unit: props.initialCoverData.declarationInfo?.unit || ''
  };
  labels.value = {
    person: props.initialCoverData.declarationInfo?.labels?.person || '申报人',
    unit: props.initialCoverData.declarationInfo?.labels?.unit || '申报单位'
  };
  declarationPosition.value.y = props.initialCoverData.declarationInfo?.position?.y || 400;

// 无论 initialCoverData 是否包含 declarationInfo，都默认显示申报信息区域
  showDeclaration.value = true;
  console.log('CoverEditor: 初始化后 showDeclaration.value:', showDeclaration.value);
  console.log('CoverEditor: 初始化后 declarationInfo.value:', JSON.parse(JSON.stringify(declarationInfo.value)));
}

// 处理取消编辑
const handleCancel = () => {
  emit('update:visible', false)
  emit('cancel')
}

// 处理确认编辑
const handleConfirm = () => {
// 准备要发送给父组件的数据
  const coverDataToEmit = {
    contentItems: contentItems.value,
    font: selectedFont.value,
    declarationInfo: {
      person: declarationInfo.value.person,
      unit: declarationInfo.value.unit,
      position: declarationPosition.value, // Include position
      labels: labels.value
    }
  };
  console.log('CoverEditor: 确认编辑，发送数据:', JSON.parse(JSON.stringify(coverDataToEmit)));
  emit('update:visible', false);
  emit('confirm', coverDataToEmit);
}

// 开始拖动申报信息
const startDraggingDeclaration = (event) => {
  if (editingLabel.value) return
  isDraggingDeclaration.value = true
  const rect = canvasContainer.value.getBoundingClientRect()
  declarationDragOffset.value = {
    y: event.clientY - rect.top - declarationPosition.value.y
  }
// 添加全局事件监听
  document.addEventListener('mousemove', handleDeclarationDrag)
  document.addEventListener('mouseup', stopDraggingDeclaration)
}

// 处理申报信息拖动
const handleDeclarationDrag = (event) => {
  if (!isDraggingDeclaration.value) return
  const rect = canvasContainer.value.getBoundingClientRect()
  const y = event.clientY - rect.top - declarationDragOffset.value.y
  declarationPosition.value = {
    y: Math.max(0, Math.min(y, rect.height - 100))
  }
}

// 停止拖动申报信息
const stopDraggingDeclaration = () => {
  isDraggingDeclaration.value = false
  document.removeEventListener('mousemove', handleDeclarationDrag)
  document.removeEventListener('mouseup', stopDraggingDeclaration)
}

// 开始编辑标签
const startEditingLabel = (type) => {
  editingLabel.value = type
  nextTick(() => {
    if (labelInput.value) {
      labelInput.value.focus()
    }
  })
}

// 完成编辑标签
const finishEditingLabel = () => {
  editingLabel.value = null
}

// 插入内容
const insertContent = (type) => {
  const newItem = {
    id: Date.now(),
    type,
    text: getDefaultText(type),
    position: { y: contentItems.value.length * 60 + 100 }
  }
  contentItems.value.push(newItem)
}

// 添加申报信息
const addDeclaration = () => {
  showDeclaration.value = true
  declarationInfo.value = {
    person: '',
    unit: ''
  }
  labels.value = {
    person: '申报人',
    unit: '申报单位'
  }
  declarationPosition.value = { y: 400 }
}

const getDefaultText = (type) => {
  switch (type) {
    case 'h1': return '一级标题'
    case 'h2': return '二级标题'
    case 'h3': return '三级标题'
    case 'text': return '插入文字'
    case 'date': return new Date().toLocaleDateString('zh-CN')
    default: return ''
  }
}

const startDragging = (item, event) => {
  if (editingItem.value) return
  draggingItem.value = item
  const rect = canvasContainer.value.getBoundingClientRect()
  dragOffset.value = {
    y: event.clientY - (rect.top + item.position.y)
  }
// 添加全局事件监听
  document.addEventListener('mousemove', handleDragging)
  document.addEventListener('mouseup', stopDragging)
}

const handleDragging = (event) => {
  if (draggingItem.value) {
    const rect = canvasContainer.value.getBoundingClientRect()
    const y = Math.max(0, Math.min(event.clientY - rect.top - dragOffset.value.y, rect.height - 30))
    draggingItem.value.position = { y }
  }
}

const stopDragging = () => {
  draggingItem.value = null
  document.removeEventListener('mousemove', handleDragging)
  document.removeEventListener('mouseup', stopDragging)
}

const startEditing = async (item) => {
  editingItem.value = item
  await nextTick()
  if (editInput.value) {
    editInput.value.focus()
  }
}

const finishEditing = () => {
  editingItem.value = null
}

const getFontSize = (type) => {
  switch (type) {
    case 'h1': return '32px'
    case 'h2': return '24px'
    case 'h3': return '20px'
    default: return '16px'
  }
}

// 移除申报信息
const removeDeclaration = () => {
  showDeclaration.value = false
  declarationInfo.value = {
    person: '',
    unit: ''
  }
  labels.value = {
    person: '申报人',
    unit: '申报单位'
  }
  declarationPosition.value = { y: 400 }
}

// 监听器
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    initializeData()
  }
})

watch(() => props.initialCoverData, (newData) => {
// Only re-initialize if the data itself changes, not just visibility
  if (props.visible && newData) {
    initializeData()
  }
}, { deep: true })

// 生命周期钩子
onMounted(() => {
  if (props.visible) {
    initializeData()
  }
})
</script>

<style scoped>
.cover-editor-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.cover-editor-modal {
  background-color: white;
  border-radius: 8px;
  width: 95%;
  max-width: 1400px;
  height: 95vh;
  display: flex;
  flex-direction: column;
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}
.modal-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}
.header-buttons {
  display: flex;
  gap: 12px;
}
.cancel-button {
  padding: 6px 16px;
  border: 1px solid #d9d9d9;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}
.cancel-button:hover {
  border-color: #00b96b;
  color: #00b96b;
}
.confirm-button {
  padding: 6px 16px;
  background: #00b96b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}
.confirm-button:hover {
  background: #009b5a;
}
.modal-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}
.history-section {
  width: 200px;
  padding: 24px;
  border-right: 1px solid #f0f0f0;
}
.history-item {
  margin-bottom: 16px;
}
.preview-thumbnail {
  width: 100%;
  height: 120px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}
.preview-section {
  flex: 1;
  padding: 24px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  overflow: auto;
}
.canvas-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.preview-area {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 595px;
  height: 842px;
  position: relative;
  border-radius: 4px;
}
.cover-preview {
  width: 100%;
  height: 100%;
  position: relative;
  padding: 40px;
  box-sizing: border-box;
}
.content-item {
  position: absolute;
  cursor: move;
  user-select: none;
  padding: 8px;
  border: 2px solid transparent;
  border-radius: 4px;
  min-width: 50px;
  z-index: 1;
  background-color: rgba(255, 255, 255, 0.8);
  transition: all 0.2s;
}
.content-item:hover {
  border-color: #00b96b;
  background-color: rgba(0, 185, 107, 0.05);
}
.content-item.dragging {
  opacity: 0.8;
  border-color: #00b96b;
  box-shadow: 0 4px 12px rgba(0, 185, 107, 0.3);
}
.edit-input {
  background: white;
  border: 2px solid #00b96b;
  padding: 4px 8px;
  outline: none;
  width: 100%;
  min-width: 100px;
  border-radius: 4px;
}
.edit-section {
  width: 320px;
  padding: 24px;
  border-left: 1px solid #f0f0f0;
  overflow-y: auto;
}
.edit-group {
  margin-bottom: 24px;
}
.group-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}
.font-options {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
}
.font-option {
  flex: 1;
}
.font-label {
  display: block;
  padding: 8px;
  text-align: center;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}
.font-label:hover {
  border-color: #00b96b;
}
.font-label.active {
  border-color: #00b96b;
  color: #00b96b;
  background-color: rgba(0, 185, 107, 0.05);
}
.font-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
.insert-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.insert-button {
  width: 100%;
  padding: 10px;
  text-align: center;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}
.insert-button:hover {
  border-color: #00b96b;
  color: #00b96b;
  background-color: rgba(0, 185, 107, 0.05);
}
.bottom-insert {
  display: flex;
  gap: 12px;
}
.bottom-insert .insert-button {
  flex: 1;
}
.insert-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
.declaration-info {
  position: absolute;
  cursor: move;
  width: 400px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
  border: 2px solid transparent;
  transition: all 0.2s;
}
.declaration-info:hover {
  border-color: #00b96b;
  background-color: rgba(0, 185, 107, 0.05);
}
.declaration-info.dragging {
  opacity: 0.8;
  border-color: #00b96b;
  box-shadow: 0 4px 12px rgba(0, 185, 107, 0.3);
}
.declaration-row {
  display: flex;
  align-items: center;
  gap: 15px;
  justify-content: flex-start;
}
.declaration-label {
  font-size: 18px;
  color: #333;
  white-space: nowrap;
  width: 100px;
  text-align: right;
  cursor: text;
  font-weight: 500;
}
.declaration-input-wrapper {
  flex: 1;
  position: relative;
}
.declaration-input-wrapper::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 1px;
  background-color: #333;
}
.declaration-input {
  width: 100%;
  padding: 8px 0;
  border: none;
  outline: none;
  background: transparent;
  font-size: 18px;
  text-align: center;
}
.declaration-input:focus + .declaration-input-wrapper::after {
  background-color: #00b96b;
  height: 2px;
}
.label-input {
  width: 100%;
  padding: 4px 8px;
  border: 2px solid #00b96b;
  outline: none;
  font-size: 18px;
  background: white;
  border-radius: 4px;
  font-weight: 500;
}
.remove-button {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.2s;
}
.remove-button:hover {
  background: #ff7875;
}
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style>
